package com.example.contact;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class TestContact {
    public static void main(String[] args) throws IOException {
        Contact.Builder builder = Contact.newBuilder();
        try {
            builder.mergeFrom(new FileInputStream("src/main/java/com/example/contact/contact.bin"));
        } catch (IOException e) {
            System.out.println("文件不存在，创建一个新文件");
        }

        builder.addPeopleInfo(createPeople());

        FileOutputStream fileOutputStream = new FileOutputStream("src/main/java/com/example/contact/contact.bin");
        builder.build().writeTo(fileOutputStream);
        fileOutputStream.close();
    }

    private static PeopleInfo createPeople() {
        PeopleInfo.Builder peopleBuilder = PeopleInfo.newBuilder();
        System.out.println("----------添加联系人----------");
        Scanner in = new Scanner(System.in);

        System.out.print("姓名为：");
        String name = in.nextLine();
        peopleBuilder.setName(name);

        System.out.print("年龄为：");
        int age = in.nextInt();
        in.nextLine();
        peopleBuilder.setAge(age);

        PeopleInfo.Phone.Builder builder = PeopleInfo.Phone.newBuilder();
        while (true) {
            System.out.print("手机号为：");
            String phone = in.nextLine();
            if (phone.isEmpty()) {
                break;
            }

            builder.setPhone(phone);
        }

        peopleBuilder.addPhone(builder);

        return peopleBuilder.build();
    }
}
